package com.atguigu.gmall.payment.service.impl;

import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.model.PaymentInfo;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @author: atguigu
 * @create: 2023-09-19 10:49
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    /**
     * 新增本地交易记录
     *
     * @param paymentInfo 本地交易记录信息
     * @param paymentType 支付方式
     */
    @Override
    public PaymentInfo savePaymentInfo(PaymentInfo paymentInfo, String paymentType) {
        //1.根据订单ID+支付方式 查询本地交易记录是否存在
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderId, paymentInfo.getOrderId());
        queryWrapper.eq(PaymentInfo::getPaymentType, paymentType);
        PaymentInfo paymentInfoDB = this.getOne(queryWrapper);
        //2.如果不存在则新增
        if (paymentInfoDB == null) {
            this.save(paymentInfo);
            return paymentInfo;
        }
        return paymentInfoDB;
    }

    /**
     * 根据订单编号+支付方式 查询本地交易记录
     * @param outTradeNo
     * @param payType
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo, String payType) {
        //1.根据订单编号+支付方式 查询本地交易记录是否存在
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOutTradeNo, outTradeNo);
        queryWrapper.eq(PaymentInfo::getPaymentType, payType);
        PaymentInfo paymentInfoDB = this.getOne(queryWrapper);
        //2.如果不存在则新增
        if (paymentInfoDB != null) {
            return paymentInfoDB;
        }
        return null;
    }

    /**
     *
     * @param orderId
     * @param payType
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(Long orderId, String payType) {
        //1.根据订单编号+支付方式 查询本地交易记录是否存在
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderId, orderId);
        queryWrapper.eq(PaymentInfo::getPaymentType, payType);
        PaymentInfo paymentInfoDB = this.getOne(queryWrapper);
        //2.如果不存在则新增
        if (paymentInfoDB != null) {
            return paymentInfoDB;
        }
        return null;
    }
}
